#!-*- encoding:utf8 -*-
import setdjango
import time, datetime

from newosmp.report.models import Report
from newosmp.settings import MonitorDb, MonitorDbType
from newosmp.monitor.models import Monitor

###########################################statistics################################
#return dict:[all, table1, table2, ... tablen)
def sum(tables , item, frm, to):
    dct = {}
    all = 0
    for id, table in tables.items():
        sql = "select  sum(%s)  from `%s` where `timestamp` > %s and `timestamp` <= %s" % (item, table, frm, to)
        print sql
        if MonitorDbType == 'MySQL':
            ret = MonitorDb.executeSqlRet(sql)
            try:
                ret = ret[0][0]
                if ret == None:
                    ret = 0
            except:
                ret = 0
            dct[id] = ret
            all += ret
    dct['all'] = all
    print dct
    return dct
           
    
 


def avg(tables, items, frm, to):
    pass

def max():
    pass

def min():
    pass

#####################################################################################

###########################################jobs######################################
def sumHourJobs(tables, item, dst,  frm=None):
    if frm == None:
        frm = int(time.time())/3600*3600 - 3600
    to = frm + 3600
    dct = sum(tables, item, frm, to)
    if not dct:
        return False
    k_lst = []
    v_lst = []
    k_lst.append("`%s`" % "timestamp")
    v_lst.append("%s" % frm)
    for k, v in dct.items():
        k_lst.append("`%s`" % k)
        v_lst.append("%s" % v)
    sql = "replace into %s (%s) values (%s)" % (dst, ",".join(k_lst), ",".join(v_lst))
    print sql
    if MonitorDbType == 'MySQL':
        if MonitorDb.executeSql(sql) == False:
            return False
    return True
    

def allSumHourJobs(frm = None):
    jobs = Report.objects.filter(statistics = 'S')
    for job in jobs:
        dst = job.table
        tables = {}
        item = job.filed
        monitors = Monitor.objects.filter(id__in = job.mid.split(','))
        for m in monitors:
            tables[str(m.id)] = m.table
        if not frm:
            sumHourJobs(tables, item, dst)
        else:
            sumHourJobs(tables, item, dst, frm)
    print "Hour jobs ok"


def sumDayJobs(t = None):
    start = getTodaySec(t)
    i = 0
    while i < 24:
        allSumHourJobs(start)
        start +=  3600
        i += 1

def getTodaySec(t = None):
    if t == None:
        today = datetime.date.today().isoformat()
    else:
        today = t
    return time.mktime( time.strptime(today, "%Y-%m-%d"))

allSumHourJobs()
#sumDayJobs("2011-12-08")
